#!/usr/bin/env bash

prog=$(basename $0)
DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)

usage()
{
	echo "usage: $prog tarfile directory" 1>&2
	exit 1
}

tarfile="$1"
directory="$2"
[ -n "$tarfile" ] || usage
[ -n "$directory" ] || usage
[ -f "$tarfile" ] || fail "tarfile $tarfile does not exist"

. "$DIR"/vms_shared || fail
. "$DIR"/vms_ids || fail
instanceids="$netbsdid"
[ -n "$instanceids" ] || fail
restart_instanceids "$instanceids"
get_summary "$instanceids"

host="root@$netbsd"
ssh_opts="-i /var/lib/jenkins/aws/ubfree.pem -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"

# It is possible for the machine to be up, but for sshd to not yet be running.
# Try multiple times for the initial connect.
attempts=0
attempts_max=50
while true ; do
	ssh $ssh_opts "$host" true && break
	attempts=$((attempts+1))
	[ "$attempts" = "$attempts_max" ] && \
		fail "Could not make initial ssh connection after $attempts"
done

ssh $ssh_opts "$host" "rm -rf $tarfile $directory /tmp/burp_ca.lock" \
	|| fail "cleaning ubuntu machine"
scp $ssh_opts "$tarfile" "$host:" \
	|| fail "scp $tarfile to ubuntu machine"
ssh $ssh_opts "$host" "tar -xjvf $tarfile" \
	|| fail "unpacking $tarfile"
# netbsd seems to need to run autoreconf first
ssh $ssh_opts "$host" \
	"cd $directory && autoreconf -vif" || fail "autoreconf -vif"
ssh $ssh_opts "$host" \
	"cd $directory && ./configure --prefix=/usr --sysconfdir=/etc/burp --localstatedir=/var && make check" \
		|| fail "make check"
ssh $ssh_opts "$host" \
	"cd $directory && cd test && make test" \
		|| fail "make test"

stop_instanceids "$instanceids"

echo "Everything succeeded."

exit 0
